﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.DwzFrame;
using NHibernate;
using ZLCMS.Business;
using ZLCMS.Data.Model;
using DotNet.Common.NHibernateUtil;
using NHibernate.Criterion;
using ZLCMS.Business.Util;

namespace ZLCMS.Web.SystemManage.Basics.File
{
    public partial class Delete : System.Web.UI.Page
    {
        public string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            FrameHelper framePage = new FrameHelper(this);
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                if (Request["ajax"] == "dels")
                {
                    String ids = Request["ids"];
                    if (!String.IsNullOrEmpty(ids))
                    {
                        String[] idArray = ids.Split(',');
                        foreach (String id in idArray)
                        {
                            try
                            {
                                DeleteFile(Int32.Parse(id), session);
                            }
                            catch (System.Exception)
                            {
                            }
                        }
                        session.Flush();
                    }
                }
                else if (!String.IsNullOrEmpty(Request["uid"]))
                {
                    try
                    {
                        DeleteFile(Int32.Parse(Request["uid"]), session);

                        session.Flush();
                    }
                    catch (System.Exception ex)
                    {
                        framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作失败-" + ex.Message });
                        return;
                    }
                }
            }
            framePage.Alert(new ReturnCode() { statusCode = 200, message = "操作成功!", navTabId = framePage.NavTabId });

        }

        protected void DeleteFile(int id, ISession session)
        {
            SysFileInfo fileDb = session.CreateCriteria<SysFileInfo>().Add(Expression.Eq("Id", id)).Add(Expression.Eq("UploadMen", _userAccount)).UniqueResult<SysFileInfo>();

            if (fileDb != null)
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(Request.ServerVariables["APPL_PHYSICAL_PATH"] + fileDb.FilePath);
                if (fileInfo.Exists)
                {
                    fileInfo.Delete();
                }
                session.Delete("from DocFile o where o.FileId=?", id, NHibernateUtil.Int32);
                session.Delete("from SysFileInfo o where o.Id=?", id, NHibernateUtil.Int32);
            }
        }
    }
}
